<?php
namespace app\modules\weixin\controllers;

use \app\common\components\BaseWebController;

use \app\common\services\weixin\RequestServices;

class JsdkController extends BaseWebController
{
	public function actionIndex(){
		$config=\Yii::$app->params['weixin'];
		$ticket=$this->getJsapiTicket();
		$noncestr=$this->getNoncestr();
		$time=time();
		$url=$this->get('url');
		$string="jsapi_ticket={$ticket}&noncestr={$noncestr}&timestamp={$time}&url={$url}";
		$signature=sha1($string);
		$data=[
			'appid'=>$config['appid'],
			'timestamp'=>$time,
			'nonceStr'=>$noncestr,
			'signature'=>$signature,
			
		];
		return $this->renderJson($data);
	}
	//获取ticket
	private function getJsapiTicket(){
		//使用yii自带的缓存
		$cache_key='wx_jsticket';
		$cache=\Yii::$app->cache;
		$ticket=$cache->get($cache_key);
		if(!$ticket){
			$access_token=RequestServices::getAccessToken();
			$res=RequestServices::send("ticket/getticket?access_token=$access_token&type=jsapi");
			if( isset($res['errcode']) && $res['errcode']==0){
				$cache->set($cache_key,$res['ticket'],$res['expires_in']-200);
				$ticket=$res['ticket'];
			}
		}
		return $ticket;	

	}
	public function getNoncestr($length=16){

		//获取随机字符串
		$chars="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
		$str='';
		for ($i=0; $i < $length; $i++) { 
			$str.=substr( $chars,mt_rand(0,strlen($chars)-1),1 );
		}
		return $str;
	}
}
?>